package cn.miaoyao.miaoyaoms.controller;
import cn.miaoyao.miaoyaoms.entity.Limits;
import cn.miaoyao.miaoyaoms.entity.Miaosample;
import cn.miaoyao.miaoyaoms.entity.QueryYaocai;
import cn.miaoyao.miaoyaoms.service.FileService;
import cn.miaoyao.miaoyaoms.service.MiaosampleService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sun
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/miaosample")
public class MiaosampleController extends BaseController{
    @Autowired
    private MiaosampleService miaosampleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private ArrayList<QueryYaocai> keys;//缓存时保存存入的key
    @Autowired
    private FileService fileService;
    /**
     * 实现分页查询
     * @param page 第几页
     * @param limit 一页几条
     * @param zhname 中文名
     * @param miaoname 苗药名
     * @param enname 英文名
     * @return
     */
    //@Cacheable(cacheNames = "sampleInfo",key = "page+'#page'")
    @GetMapping("sampleInfo")
    public String getInfo(@RequestParam(value = "page" ,defaultValue="1") String page,
                          @RequestParam(value = "limit",defaultValue = "10") String limit,
                          @RequestParam(value = "zhname",defaultValue = "") String zhname,
                          @RequestParam(value = "miaoname",defaultValue = "")String miaoname,
                          @RequestParam(value = "enname",defaultValue = "")String enname,
                          HttpServletRequest request
                          ) {
        LambdaQueryWrapper<Miaosample> lsw = new LambdaQueryWrapper<>();
        Page<Miaosample> pageinfo = new Page<>(Long.valueOf(page), Long.valueOf(limit));
        Limits limits = (Limits) request.getSession().getAttribute("limits");
        HashMap<String, Object> map = new HashMap<>();
        //定义权限变量
        Integer deletePermission = 0,updatePermission=0,addPermission=0;
        map.put("code",0);
        map.put("msg","");
        if ("".equals(zhname)) {
            //全部查询出来,并分页
            miaosampleService.page(pageinfo,null);
        } else {
            lsw=lsw.like(Miaosample::getZhname, zhname);
            if(!"".equals(miaoname))
                lsw=lsw.like(Miaosample::getMiaoname,miaoname);
            if(!"".equals(enname))
                lsw=lsw.like(Miaosample::getEnname,enname);
            //进行分页查询
            miaosampleService.page(pageinfo, lsw);
           // System.out.println(pageinfo.getRecords());
        }
        //判断权限
        if(limits.getAddmiaosample()==1)
            addPermission=1;
        if(limits.getDeletemiaosample()==1)
           deletePermission=1;
        if(limits.getUpdatemiaosample()==1)
           updatePermission=1;
        map.put("addPermission",addPermission);//添加权限
        map.put("deletePermission",deletePermission);//删除权限
        map.put("updatePermission",updatePermission);//修改权限
        map.put("count",pageinfo.getTotal());//总条数
        map.put("data",pageinfo.getRecords());//获取的数据
        return JSON.toJSONString(map);
    }

    /**
     * 修改药材信息
     * @param miaosample
     * @return
     */
    @PostMapping("update")
    public boolean updateInfo(Miaosample miaosample){
        LambdaQueryWrapper<Miaosample> msw = new LambdaQueryWrapper<>();
        if(!ObjectUtils.isEmpty(miaosample)) {
            msw.eq(Miaosample::getId, miaosample.getId());
            boolean updateSuccess = miaosampleService.update(miaosample, msw);
            if(updateSuccess){
                return true;
            }
        }
        return false;
    }
    /**
     * 根据id删除数据，这里是逻辑删除，不可能真正删除掉数据，方便后期使用到。
     * @param mid
     * @return
     */
    @PostMapping("delete")
    public boolean delete(Integer mid,HttpServletRequest request){
        LambdaQueryWrapper<Miaosample> lsw = new LambdaQueryWrapper<>();//定义查询条件对象。
        if(mid!=null) {
            Miaosample one = miaosampleService.getOne(lsw.eq(Miaosample::getId, mid));
            String filePath = one.getPicture();
            super.deleteFile(request,filePath);//进行图片删除。
            return miaosampleService.removeById(mid);
        }
        return false;
    }


    /**
     * 执行批量删除
     * @param ids
     * @return
     */
    @CacheEvict(cacheNames = "sampleInfo",allEntries = true)//清空所有的缓存
    @PostMapping("deleteBatch")
    public boolean deleteBatch( @RequestBody List<Integer> ids,HttpServletRequest request){
        LambdaQueryWrapper<Miaosample> lsw = new LambdaQueryWrapper<>();
        for(Integer id:ids){
            lsw.eq(Miaosample::getId,id);
            String filepath = miaosampleService.getOne(lsw).getPicture();
            super.deleteFile(request,filepath);//进行对应的图片删除
        }
       return miaosampleService.removeByIds(ids);
    }

    /**
     * 药材图片上传，数据信息发送给前端页面
     * @param file
     * @return
     */
    @PostMapping(value = "uploadImage")
    public String getImageInfo(@RequestBody MultipartFile file,HttpServletRequest request){
        HashMap<Object, Object> map = new HashMap<>();
        HashMap<Object, Object> map1 = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        if((!file.isEmpty())&&file.getSize()>0){
            //创建上传图片的新名字
            String newFileName = super.createNewFileName(file);
            String filePath=super.saveFile(newFileName,request,file);//进行文件保存,返回相对路径
            map1.put("url",filePath);
            map.put("data",map1);
            System.out.println(JSON.toJSONString(map));
            return JSON.toJSONString(map);
        }
        return null;
    }
    //设置目录下的子文件夹，如果有就指定，没有就创建。
    @Override
    protected String getDir() {
        return "imgs/";
    }

    /**
     * 药材添加
     * @param miaosample
     * @return
     */
    @PostMapping("add")
    public boolean addInfo( Miaosample miaosample){
        boolean save=false;
        LambdaQueryWrapper<Miaosample> msw = new LambdaQueryWrapper<>();
        //添加查询条件
        msw.eq(Miaosample::getZhname,miaosample.getZhname()).or().eq(Miaosample::getEnname,miaosample.getEnname()).or().eq(Miaosample::getMiaoname,miaosample.getMiaoname());
        Miaosample miao = miaosampleService.getOne(msw);
        System.out.println(miaosample);
        if(miao==null){
            miaosample.setCreateTime(System.currentTimeMillis());
            if(miaosample!=null) {
                save= miaosampleService.save(miaosample);//将其保存到数据库中
            }
            if(save) {
                return true;
            }
        }
        return false;
    }

    /**
     * 药材查询功能实现
     * @param yaocai
     * @return
     */
    @PostMapping("searchYaocai")
    public String getYaocaiInfo( QueryYaocai yaocai){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<Miaosample> query = new QueryWrapper<>();
        query.eq(yaocai.getLeibie(),yaocai.getSearchContext());
        Miaosample miaoyao = miaosampleService.getOne(query);
        System.out.println(miaoyao);
        return JSON.toJSONString(miaoyao);
    }
    @GetMapping("getinfo/{id}")
    public String getInfo(@PathVariable Integer id){
        Miaosample miao = miaosampleService.getById(id);
        if(!ObjectUtils.isEmpty(miao)){
            return JSON.toJSONString(miao);
        }
        return null;
    }

    /**
     * excel文件导入
     * @param multipartFile
     * @return
     */
    @PostMapping("/loadFile")
    public boolean loadFile(@RequestPart(value = "file")MultipartFile multipartFile){
      return  fileService.importExcel(multipartFile,miaosampleService);
    }
}

